package com.huawei.aiservice.impl;

import com.huawei.aiservice.constants.ResponseCode;
import com.huawei.aiservice.entity.pojo.FileEntity;
import com.huawei.aiservice.entity.pojo.Report;
import com.huawei.aiservice.entity.pojo.Rule;
import com.huawei.aiservice.entity.vo.*;
import com.huawei.aiservice.enums.ReportStatus;
import com.huawei.aiservice.exception.BusinessException;
import com.huawei.aiservice.impl.strategy.RuleContext;
import com.huawei.aiservice.impl.strategy.RuleFacotry;
import com.huawei.aiservice.impl.strategy.RuleStrategy;
import com.huawei.aiservice.service.*;

import com.huawei.aiservice.utils.TimeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class FileServiceImpl implements FileService {
    @Resource
    private ReportService reportService;

    @Resource
    private FileEntityService fileEntityService;

    @Resource
    private RuleService ruleService;

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Resource
    private DefectService defectService;

    @Resource
    private FileRuleService fileRuleService;

    @Override
    public Response<String> check(MultipartFile[] files, String fragment, Map<String, String> headers, String fullPath) {
        if (!StringUtils.isBlank(fragment)) {
            if (files.length != 1) {
                return Response.failed(ResponseCode.PARAM_ERROR, "fragment is not blank but have more than 1 files");
            }
        }

        boolean isValid = checkValidFile(files);
        if (!isValid) {
            return Response.failed("files are not valid");
        }

        //TODO 待实现:根据header获取用户
        int userId = 1;

        // 初始化report
        Report report = new Report(userId, TimeUtils.getCurrentTime(), ReportStatus.PROCESSING);
        reportService.save(report);

        try {
            // 将文件保存到本地
            // TODO 保存文件的时候可能会重名
            Map<MultipartFile, String> file2path = saveFile(files);
            Map<MultipartFile, FileEntity> file2Entity = new HashMap<>();
            saveFileEntity(report.getReportId(), file2path, file2Entity, fullPath);

            // 获取所有规则
            List<Rule> ruleList = ruleService.list();
            if (ruleList.isEmpty()) {
                report.setStatus(ReportStatus.SUCCESS);
                return Response.success("success");
            }

            // 每个规则，分别处理所有文件
            for (Rule rule : ruleList) {
                RuleStrategy ruleStrategy = RuleFacotry.getRuleStrategy(rule);
                RuleContext ruleContext = new RuleContext(ruleStrategy, file2Entity, taskExecutor, rule, defectService, fragment, fileRuleService);
                ruleContext.executeStrategy();
            }
        } catch (Exception e) {
            report.setStatus(ReportStatus.FAIL);
            reportService.updateById(report);
            throw new BusinessException("some things error", e);
        }

        return Response.success("success");
    }

    private void saveFileEntity(int reportId, Map<MultipartFile, String> file2path, Map<MultipartFile, FileEntity> fileEntityList,
                                String fullPath) {
        for (MultipartFile file : file2path.keySet()) {
            String filePath = file2path.get(file);
            FileEntity fileEntity = new FileEntity(reportId, fullPath, filePath);
            fileEntityService.save(fileEntity);
            fileEntityList.put(file, fileEntity);
        }
    }

    private Map<MultipartFile, String> saveFile(MultipartFile[] files) {
        Map<MultipartFile, String> filePathMap = new HashMap<>();
        String baseDir = "C:\\code\\check_file";

        // 确保目标目录存在
        File dir = new File(baseDir);
        if (!dir.exists()) {
            dir.mkdirs(); // 创建目录
        }

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue; // 跳过空文件
            }
            String originalFilename = file.getOriginalFilename(); // 获取文件名
            String filePath = baseDir + File.separator + originalFilename; // 文件保存路径

            try {
                file.transferTo(new File(filePath)); // 保存文件
                filePathMap.put(file, filePath); // 记录文件路径
            } catch (IOException e) {
                throw new BusinessException("文件保存失败", e);
            }
        }

        return filePathMap;
    }

    private boolean checkValidFile(MultipartFile[] files) {
        return true;
    }

    @Override
    public Response<ReportDetail> detail(int reportId) {
        return null;
    }
}
